# -*- coding: utf-8 -*-
# @file    : sub_process
# @Date    : 2020/12/14
# @Author  :
# @Version : 1.0.0
import os
import sys

from . import MacroThread, ListenerThread, HotKey
from .config import Config
from .action import ActionGroup, StoreActionGroup
from .util import options

macro_th = None
listener_th = None


def on_activate(hot_key):
    action_group = hot_key.action_group
    if not action_group:
        return
    if action_group.running:
        macro_th.stop_act_group(action_group)
    else:
        macro_th.run_act_group(action_group)


def build_hot_keys(config):
    print("[全局热键] 构建中 ...")
    hot_keys = []
    for conf in config.data:
        _hot_key = conf['hotKey']
        hot_key = HotKey(HotKey.parse(_hot_key), on_activate)
        if "storeActionGroup" in conf:
            _store_action_group = conf['storeActionGroup']
            store_action_group = StoreActionGroup(
                name=_store_action_group['name'],
                wh=_store_action_group['warehouse'],
                bp=_store_action_group["backpack"]
            )
            hot_key.action_group = store_action_group
            print("[全局热键] 热键: %s  动作组: %s" % (_hot_key, store_action_group.name))
        elif "actionGroup" in conf:
            _action_group = conf['actionGroup']
            action_group = ActionGroup(
                name=_action_group['name'],
                repeat=_action_group['repeat'],
                interval=_action_group['interval'],
                expr=_action_group['expr']
            )
            hot_key.action_group = action_group
            print("[全局热键] 热键: %s  动作组: %s" % (_hot_key, action_group.name))

        hot_keys.append(hot_key)

    print("[全局热键] 全部完成! (%s个)" % len(hot_keys))
    return hot_keys


def main():
    try:
        print("*" * 50)
        print("[系统] 欢迎使用 Auto Macro 软件!")
        config_path = options.get("--config", './config.yml')
        config = Config(config_path)
        hot_keys = build_hot_keys(config)
        if "--stop-after-init" in options:
            # 用于测试配置文件
            print('[系统] 初始化完成, 自动退出')
            print("*" * 50)
            sys.exit(0)
        global macro_th, listener_th
        macro_th = MacroThread()
        listener_th = ListenerThread(hot_keys)
        macro_th.start()
        listener_th.start()
        print("[系统] 一切准备就绪!")
        print("*" * 50)
    except Exception as e:
        print('发生非预期的错误:')
        print(e)
        print('程序即将退出!')
        os.system('pause')


if __name__ == '__main__':
    main()
